package cn.android666.recorddemowithnoise

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat

class VoiceCallService : Service() {
    companion object {
        private const val CHANNEL_ID = "VoiceCallServiceChannel"
        private const val NOTIFICATION_ID = 1
    }

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val notification = createNotification()
        startForeground(NOTIFICATION_ID, notification)
        return START_STICKY // 服务被杀死后会尝试重启
    }

    override fun onDestroy() {
        super.onDestroy()
        stopForeground(true)
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "语音通话服务",
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "用于在录音和播放音频时保持应用活跃"
            }

            val manager = getSystemService(NotificationManager::class.java)
            manager.createNotificationChannel(channel)
        }
    }

    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("语音通话运行中")
            .setContentText("正在录音和播放音频")
            .setSmallIcon(R.drawable.ic_launcher_foreground) // 使用默认图标
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
    }
}